﻿using System;
using System.Web.UI.WebControls;
using Business;
using System.Globalization;
using EntitiesTM;
using System.Data;

namespace TimeWork
{
    public partial class TimeWeek : System.Web.UI.Page
    {
        public static DateTime dateRegister = DateTime.Now;
         

        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["email"] != null)
            {
                if (!IsPostBack)
                {
                    
                    dateRegister = DateTime.Now;
                    fillInformation();
                    BindDdlCode1();  
                    //BindDdlActivity(Int32.Parse(ddlProject.SelectedValue));
                    fillGrid();
                }
            }
        }

        public EnDate GetDate()
        {
            return new EnDate(dateRegister);
        }

        private void fillGrid()
        {
            DateTime firstDay = GetFirstDayOfWeek(dateRegister);
            lblDateRegister.Text = "Từ " + firstDay.ToString("dd/MM", new CultureInfo("vi-VN"))+" đến "+firstDay.AddDays(6).ToString("dd/MM", new CultureInfo("vi-VN"));
            gvRegisterWeek.DataSource = BuTimeWeek.selRegisterWeek(firstDay.ToString(), Session["email"].ToString(), Session["companyid"].ToString());
            gvRegisterWeek.DataBind();
        }

        //private void BindDdlProject()
        //{

        //    Dictionary<string, string> data = BuProject.selProjectRegisterTree(Session["email"].ToString());
        //    ListItem item;
        //    foreach (KeyValuePair<string, string> pair in data)
        //    {
        //        item = new ListItem(pair.Value, pair.Key);
        //        ddlProject.Items.Add(item);
        //    }

        //}
        private void BindDdlCode4(int projectID)
        {
            EnProject project = new EnProject();
            project.projectID = projectID;
            ddlCode4.DataSource = BuProject.selActivityByProjectExceptID(project, Session["companyid"].ToString());
            ddlCode4.DataTextField = "ActivityName";
            ddlCode4.DataValueField = "ActivityID";
            ddlCode4.DataBind();
        }

        private void BindDdlCode1()
        {
            ddlCode1.DataSource = BuProject.selProjectRegisterTmp(lblEmail.Text, 1, 0, Session["companyid"].ToString());
            ddlCode1.DataTextField = "ProjectName";
            ddlCode1.DataValueField = "ProjectID";
            ddlCode1.DataBind();
            ddlCode1.Items.Insert(0, new ListItem("--- Chọn sản phẩm ---", "0"));
            //ddlCode1.SelectedValue = "0";

        }
        private void BindDdlCode2(int parentID)
        {
            ddlCode2.DataSource = BuProject.selProjectRegisterTmp(lblEmail.Text, 2, parentID, Session["companyid"].ToString());
            ddlCode2.DataTextField = "ProjectName";
            ddlCode2.DataValueField = "ProjectID";
            ddlCode2.DataBind();
            ddlCode2.Items.Insert(0, new ListItem("--- Chọn sản phẩm ---", "0"));
            ddlCode2.SelectedValue = "0";
        }
        private void BindDdlCode3(int parentID)
        {
            ddlCode3.DataSource = BuProject.selProjectRegisterTmp(lblEmail.Text, 3, parentID, Session["companyid"].ToString());
            ddlCode3.DataTextField = "ProjectName";
            ddlCode3.DataValueField = "ProjectID";
            ddlCode3.DataBind();
            ddlCode3.Items.Insert(0, new ListItem("--- Chọn sản phẩm ---", "0"));
            ddlCode3.SelectedValue = "0";
        }
        //private void BindDdlActivity(int projectID)
        //{
        //    EnProject project = new EnProject();
        //    project.projectID = projectID;
        //    ddlActivity.DataSource = BuProject.selActivityByProjectExceptID(project);
        //    ddlActivity.DataTextField = "ActivityName";
        //    ddlActivity.DataValueField = "ActivityID";
        //    ddlActivity.DataBind();
        //}

        //protected void ddlProject_SelectedIndexChanged(object sender, EventArgs e)
        //{
        //    string itemSelected = ddlProject.SelectedValue;
        //    BindDdlActivity(Int32.Parse(itemSelected));
        //}

        private void fillInformation()
        {
            if (Session["email"] != null)
            {
                string email = Session["email"].ToString();
                EnStaff staff = BuStaff.GetStaffByEmailOpt(email, Session["companyid"].ToString());
                lblName.Text = staff.staffName;
                lblEmail.Text = email;
            }
            
        }


        protected void Calendar_SelectionChanged(object sender, EventArgs e)
        {
            dateRegister = Calendar.SelectedDate;
            fillGrid();
        }

        public static int GetWeekNumber(DateTime dtPassed)
        {
            CultureInfo ciCurr = CultureInfo.CurrentCulture;
            int weekNum = ciCurr.Calendar.GetWeekOfYear(dtPassed, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);
            return weekNum;
        }
        public DateTime GetFirstDayOfWeek(DateTime dt)
        {
            int day = (int) dt.DayOfWeek;
            if (day == 0)
            {
                return dt.AddDays(-6);
            }
            return dt.AddDays(1 - day);
        }

        protected void Calendar_DayRender(object sender, DayRenderEventArgs e)
        {
            
        }
        private string genScript(string comment, string time, string projectName)
        {
            string script = String.Empty;
            script += "RelatedTextBox='" + comment + "';document.getElementById('MainContent_txtComment').style.display='inline';document.getElementById('MainContent_lblComment').style.display='inline';";
            script += "document.getElementById('MainContent_lblComment').innerHTML='<b>Ghi chú: </b><i>'+document.getElementById('" + time + "').innerHTML+' -- '+ document.getElementById('" + projectName + "').innerHTML+'</i>';";
            script += "document.getElementById('MainContent_txtComment').value= document.getElementById('" + comment + "').value;";    
            return script;
        }

        private int totalHourMon = 0;
        private int totalMinuteMon = 0;
        private int totalHourTue = 0;
        private int totalMinuteTue = 0;
        private int totalHourWed = 0;
        private int totalMinuteWed = 0;
        private int totalHourThu = 0;
        private int totalMinuteThu = 0;
        private int totalHourFri = 0;
        private int totalMinuteFri = 0;
        private int totalHourSat = 0;
        private int totalMinuteSat = 0;
        private int totalHourSun = 0;
        private int totalMinuteSun = 0;
        private int totalTimeHour = 0;
        private int totalTimeMinute = 0;
        protected void gvRegisterWeek_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                // Thu 2
                TextBox txtTimeReport = (TextBox)e.Row.FindControl("txtTimeReportMon");
                Label lblTime = (Label)e.Row.FindControl("lblTimeMon");
                Label lblProjectName = (Label)e.Row.FindControl("lblProjectName");
                HiddenField hd = (HiddenField)e.Row.FindControl("hdMon");
                txtTimeReport.Attributes.Add("onfocus", genScript(hd.ClientID, lblTime.ClientID, lblProjectName.ClientID));
                if (!txtTimeReport.Text.Equals(""))
                {
                    string[] result = txtTimeReport.Text.Split(':');
                    totalHourMon += Int32.Parse(result[0]);
                    totalMinuteMon += Int32.Parse(result[1]);
                }


                // Thu 3
                txtTimeReport = (TextBox)e.Row.FindControl("txtTimeReportTue");
                hd = (HiddenField)e.Row.FindControl("hdTue");
                lblTime = (Label)e.Row.FindControl("lblTimeTue");
                txtTimeReport.Attributes.Add("onfocus", genScript(hd.ClientID, lblTime.ClientID, lblProjectName.ClientID));
                if (!txtTimeReport.Text.Equals(""))
                {
                    string[] result = txtTimeReport.Text.Split(':');
                    totalHourTue += Int32.Parse(result[0]);
                    totalMinuteTue += Int32.Parse(result[1]);
                }

                // Thu 4
                txtTimeReport = (TextBox)e.Row.FindControl("txtTimeReportWed");
                hd = (HiddenField)e.Row.FindControl("hdWed");
                lblTime = (Label)e.Row.FindControl("lblTimeWed");
                txtTimeReport.Attributes.Add("onfocus", genScript(hd.ClientID, lblTime.ClientID, lblProjectName.ClientID));
                if (!txtTimeReport.Text.Equals(""))
                {
                    string[] result = txtTimeReport.Text.Split(':');
                    totalHourWed += Int32.Parse(result[0]);
                    totalMinuteWed += Int32.Parse(result[1]);
                }
                // Thu 5
                txtTimeReport = (TextBox)e.Row.FindControl("txtTimeReportThu");
                hd = (HiddenField)e.Row.FindControl("hdThu");
                lblTime = (Label)e.Row.FindControl("lblTimeThu");
                txtTimeReport.Attributes.Add("onfocus", genScript(hd.ClientID, lblTime.ClientID, lblProjectName.ClientID));
                if (!txtTimeReport.Text.Equals(""))
                {
                    string[] result = txtTimeReport.Text.Split(':');
                    totalHourThu += Int32.Parse(result[0]);
                    totalMinuteThu += Int32.Parse(result[1]);
                }
                // Thu 6
                txtTimeReport = (TextBox)e.Row.FindControl("txtTimeReportFri");
                hd = (HiddenField)e.Row.FindControl("hdFri");
                lblTime = (Label)e.Row.FindControl("lblTimeFri");
                txtTimeReport.Attributes.Add("onfocus", genScript(hd.ClientID,lblTime.ClientID, lblProjectName.ClientID));
                if (!txtTimeReport.Text.Equals(""))
                {
                    string[] result = txtTimeReport.Text.Split(':');
                    totalHourFri += Int32.Parse(result[0]);
                    totalMinuteFri += Int32.Parse(result[1]);
                }
                // Thu 7
                txtTimeReport = (TextBox)e.Row.FindControl("txtTimeReportSat");
                hd = (HiddenField)e.Row.FindControl("hdSat");
                lblTime = (Label)e.Row.FindControl("lblTimeSat");
                txtTimeReport.Attributes.Add("onfocus", genScript(hd.ClientID, lblTime.ClientID, lblProjectName.ClientID));
                if (!txtTimeReport.Text.Equals(""))
                {
                    string[] result = txtTimeReport.Text.Split(':');
                    totalHourSat += Int32.Parse(result[0]);
                    totalMinuteSat += Int32.Parse(result[1]);
                }
                // Chu nhat
                txtTimeReport = (TextBox)e.Row.FindControl("txtTimeReportSun");
                hd = (HiddenField)e.Row.FindControl("hdSun");
                lblTime = (Label)e.Row.FindControl("lblTimeSun");
                txtTimeReport.Attributes.Add("onfocus", genScript(hd.ClientID, lblTime.ClientID, lblProjectName.ClientID));
                if (!txtTimeReport.Text.Equals(""))
                {
                    string[] result = txtTimeReport.Text.Split(':');
                    totalHourSun += Int32.Parse(result[0]);
                    totalMinuteSun += Int32.Parse(result[1]);
                }

            }

            if (e.Row.RowType == DataControlRowType.Footer)
            {
                if (totalMinuteMon >= 60)
                {
                    int addHour = totalMinuteMon / 60;
                    totalMinuteMon -= 60 * addHour;
                    totalHourMon += addHour;
                }
                Label lblSum = (Label)e.Row.FindControl("lblSumMon");
                lblSum.Text = totalHourMon.ToString() + ":" + totalMinuteMon.ToString();
                totalTimeHour += totalHourMon;
                totalTimeMinute += totalMinuteMon;

                if (totalMinuteTue >= 60)
                {
                    int addHour = totalMinuteTue / 60;
                    totalMinuteTue -= 60 * addHour;
                    totalHourTue += addHour;
                }
                lblSum = (Label)e.Row.FindControl("lblSumTue");
                lblSum.Text = totalHourTue.ToString() + ":" + totalMinuteTue.ToString();
                totalTimeHour += totalHourTue;
                totalTimeMinute += totalMinuteTue;

                if (totalMinuteWed >= 60)
                {
                    int addHour = totalMinuteWed / 60;
                    totalMinuteWed -= 60 * addHour;
                    totalHourWed += addHour;
                }
                lblSum = (Label)e.Row.FindControl("lblSumWed");
                lblSum.Text = totalHourWed.ToString() + ":" + totalMinuteWed.ToString();
                totalTimeHour += totalHourWed;
                totalTimeMinute += totalMinuteWed;

                if (totalMinuteThu >= 60)
                {
                    int addHour = totalMinuteThu / 60;
                    totalMinuteThu -= 60 * addHour;
                    totalHourThu += addHour;
                }
                lblSum = (Label)e.Row.FindControl("lblSumThu");
                lblSum.Text = totalHourThu.ToString() + ":" + totalMinuteThu.ToString();
                totalTimeHour += totalHourThu;
                totalTimeMinute += totalMinuteThu;

                if (totalMinuteFri >= 60)
                {
                    int addHour = totalMinuteFri / 60;
                    totalMinuteFri -= 60 * addHour;
                    totalHourFri += addHour;
                }
                lblSum = (Label)e.Row.FindControl("lblSumFri");
                lblSum.Text = totalHourFri.ToString() + ":" + totalMinuteFri.ToString();
                totalTimeHour += totalHourFri;
                totalTimeMinute += totalMinuteFri;

                if (totalMinuteSat >= 60)
                {
                    int addHour = totalMinuteSat / 60;
                    totalMinuteSat -= 60 * addHour;
                    totalHourSat += addHour;
                }
                lblSum = (Label)e.Row.FindControl("lblSumSat");
                lblSum.Text = totalHourSat.ToString() + ":" + totalMinuteSat.ToString();
                totalTimeHour += totalHourSat;
                totalTimeMinute += totalMinuteSat;

                if (totalMinuteSun >= 60)
                {
                    int addHour = totalMinuteSun / 60;
                    totalMinuteSun -= 60 * addHour;
                    totalHourSun += addHour;
                }
                lblSum = (Label)e.Row.FindControl("lblSumSun");
                lblSum.Text = totalHourSun.ToString() + ":" + totalMinuteSun.ToString();
                totalTimeHour += totalHourSun;
                totalTimeMinute += totalMinuteSun;

                if (totalTimeMinute >= 60)
                {
                    int addHour = totalTimeMinute / 60;
                    totalTimeMinute -= 60 * addHour;
                    totalTimeHour += addHour;
                }
                Label lblSumTime = (Label)e.Row.FindControl("lblSum");
                lblSumTime.Text = totalTimeHour.ToString() + ":" + totalTimeMinute.ToString();
            }
        }

        private void update(GridViewRow row,Label activityID,string txtTimeReport, string hdIn, string lblIDIn,int day)
        {
            TextBox time = row.FindControl(txtTimeReport) as TextBox;
            HiddenField hd = row.FindControl(hdIn) as HiddenField;
            if (!time.Text.Equals("") && !time.Text.Equals("00:00"))
            {
                string[] result = time.Text.Split(':');

                EnSA sa = new EnSA();
                try
                {
                    sa.saTimeReportHour = Int32.Parse(result[0]);
                    sa.saTimeReportMinute = Int32.Parse(result[1]);
                    sa.saDetails = hd.Value;
                    sa.saID = Int32.Parse(((Label)row.FindControl(lblIDIn)).Text);
                    if (sa.saID == 0)
                    {
                        sa.saActivityID = Int32.Parse(activityID.Text);
                        sa.saTimeReportHour = Int32.Parse(result[0]);
                        sa.saTimeReportMinute = Int32.Parse(result[1]);
                        sa.saDate = GetFirstDayOfWeek(dateRegister).AddDays(day);
                        sa.email = lblEmail.Text;
                        //sa.saDetails = "";
                        BuTimeDay.insRegisterDay2(sa, Session["companyid"].ToString());
                    }
                    else
                    {
                        BuTimeDay.updRegisterDay2(sa, Session["companyid"].ToString());
                    }
                }
                catch { }
            }
        }
        protected void btnUpdate_Click(object sender, EventArgs e)
        {
            // Duyet tat ca cac o chua du lieu trong Grid, bo qua cac o trong va 00
            foreach (GridViewRow row in gvRegisterWeek.Rows)
            {
                Label activityID = row.FindControl("lblActivityID") as Label;
                update(row, activityID, "txtTimeReportMon", "hdMon", "lblIDMon",0);
                update(row, activityID, "txtTimeReportTue", "hdTue", "lblIDTue",1);
                update(row, activityID, "txtTimeReportWed", "hdWed", "lblIDWed",2);
                update(row, activityID, "txtTimeReportThu", "hdThu", "lblIDThu",3);
                update(row, activityID, "txtTimeReportFri", "hdFri", "lblIDFri",4);
                update(row, activityID, "txtTimeReportSat", "hdSat", "lblIDSat",5);
                update(row, activityID, "txtTimeReportSun", "hdSun", "lblIDSun",6);

                // Xoa dong
                CheckBox cbDelele = row.FindControl("cbDelete") as CheckBox;
                if (cbDelele.Checked)
                {
                    EnSA sa = new EnSA();
                    try
                    {
                        sa.saID = Int32.Parse(((Label)row.FindControl("lblIDMon")).Text);
                        if (sa.saID != 0)
                        {
                            BuTimeDay.delRegisterDay(sa, Session["companyid"].ToString());
                        }

                        sa.saID = Int32.Parse(((Label)row.FindControl("lblIDTue")).Text);
                        if (sa.saID != 0)
                        {
                            BuTimeDay.delRegisterDay(sa,Session["companyid"].ToString());
                        }

                        sa.saID = Int32.Parse(((Label)row.FindControl("lblIDWed")).Text);
                        if (sa.saID != 0)
                        {
                            BuTimeDay.delRegisterDay(sa, Session["companyid"].ToString());
                        }

                        sa.saID = Int32.Parse(((Label)row.FindControl("lblIDThu")).Text);
                        if (sa.saID != 0)
                        {
                            BuTimeDay.delRegisterDay(sa, Session["companyid"].ToString());
                        }

                        sa.saID = Int32.Parse(((Label)row.FindControl("lblIDFri")).Text);
                        if (sa.saID != 0)
                        {
                            BuTimeDay.delRegisterDay(sa, Session["companyid"].ToString());
                        }

                        sa.saID = Int32.Parse(((Label)row.FindControl("lblIDSat")).Text);
                        if (sa.saID != 0)
                        {
                            BuTimeDay.delRegisterDay(sa, Session["companyid"].ToString());
                        }

                        sa.saID = Int32.Parse(((Label)row.FindControl("lblIDSun")).Text);
                        if (sa.saID != 0)
                        {
                            BuTimeDay.delRegisterDay(sa, Session["companyid"].ToString());
                        }
                    }
                    catch { }
                }
            }
            fillGrid();
        }


        protected void btnAdd_Click(object sender, EventArgs e)
        {
            lblErrorNotice.Text = String.Empty;

            EnSA sa = new EnSA();

            try
            {
                sa.saActivityID = Int32.Parse(ddlCode4.SelectedValue);
                sa.saTimeReportHour = 0;
                sa.saTimeReportMinute = 0;
                sa.saDate = GetFirstDayOfWeek(dateRegister).AddDays(0);
                sa.email = lblEmail.Text;
                sa.saDetails = "";
                BuTimeDay.insRegisterWeek(sa, Session["companyid"].ToString());
                sa.saDate = GetFirstDayOfWeek(dateRegister).AddDays(1);
                BuTimeDay.insRegisterWeek(sa, Session["companyid"].ToString());
                sa.saDate = GetFirstDayOfWeek(dateRegister).AddDays(2);
                BuTimeDay.insRegisterWeek(sa, Session["companyid"].ToString());
                sa.saDate = GetFirstDayOfWeek(dateRegister).AddDays(3);
                BuTimeDay.insRegisterWeek(sa, Session["companyid"].ToString());
                sa.saDate = GetFirstDayOfWeek(dateRegister).AddDays(4);
                BuTimeDay.insRegisterWeek(sa, Session["companyid"].ToString());
                sa.saDate = GetFirstDayOfWeek(dateRegister).AddDays(5);
                BuTimeDay.insRegisterWeek(sa, Session["companyid"].ToString());
                sa.saDate = GetFirstDayOfWeek(dateRegister).AddDays(6);
                BuTimeDay.insRegisterWeek(sa, Session["companyid"].ToString());
            }
            catch {
                lblErrorNotice.Text = "Sản phẩm này chưa có công việc!";
            }
            fillGrid();
        }

        protected void btnCopy_Click(object sender, EventArgs e)
        {
            EnSA sa = new EnSA();

            DataTable items = BuTimeDay.selRegisterWeekCopy(GetFirstDayOfWeek(dateRegister).AddDays(-7).ToString(), lblEmail.Text, Session["companyid"].ToString());
            int count = items.Rows.Count;
            if (count > 0)
            {
                for (int i = 0; i < count; i++)
                {

                    sa.saActivityID = Int32.Parse(items.Rows[i]["SAActivityID"].ToString());
                    sa.saTimeReportHour = 0;
                    sa.saTimeReportMinute = 0;
                    sa.email = lblEmail.Text;
                    sa.saDetails = "";
                    sa.saDate = GetFirstDayOfWeek(dateRegister).AddDays(0);
                    BuTimeDay.insRegisterWeek(sa, Session["companyid"].ToString());
                    sa.saDate = GetFirstDayOfWeek(dateRegister).AddDays(1);
                    BuTimeDay.insRegisterWeek(sa, Session["companyid"].ToString());
                    sa.saDate = GetFirstDayOfWeek(dateRegister).AddDays(2);
                    BuTimeDay.insRegisterWeek(sa, Session["companyid"].ToString());
                    sa.saDate = GetFirstDayOfWeek(dateRegister).AddDays(3);
                    BuTimeDay.insRegisterWeek(sa, Session["companyid"].ToString());
                    sa.saDate = GetFirstDayOfWeek(dateRegister).AddDays(4);
                    BuTimeDay.insRegisterWeek(sa, Session["companyid"].ToString());
                    sa.saDate = GetFirstDayOfWeek(dateRegister).AddDays(5);
                    BuTimeDay.insRegisterWeek(sa, Session["companyid"].ToString());
                    sa.saDate = GetFirstDayOfWeek(dateRegister).AddDays(6);
                    BuTimeDay.insRegisterWeek(sa, Session["companyid"].ToString());
                }
            }
            fillGrid();
        }

        protected void ddlCode1_SelectedIndexChanged(object sender, EventArgs e)
        {
            ddlCode2.Visible = false;
            ddlCode3.Visible = false;
            ddlCode4.Visible = false;
            if (!ddlCode1.SelectedValue.Equals("0"))
            {
                ddlCode2.Visible = true;
                BindDdlCode2(Int32.Parse(ddlCode1.SelectedValue));
            }
            else
            {
                BindDdlCode4(0);
            }
        }

        protected void ddlCode2_SelectedIndexChanged(object sender, EventArgs e)
        {
            ddlCode2.Visible = true;
            ddlCode3.Visible = false;
            ddlCode4.Visible = false;
            if (!ddlCode2.SelectedValue.Equals("0"))
            {
                //ddlCode2.Visible = true;
                ddlCode3.Visible = true;
                BindDdlCode3(Int32.Parse(ddlCode2.SelectedValue));
            }
            else
            {
                BindDdlCode4(0);
            }
        }

        protected void ddlCode3_SelectedIndexChanged(object sender, EventArgs e)
        {
            ddlCode2.Visible = true;
            ddlCode3.Visible = true;
            ddlCode4.Visible = false;
            if (!ddlCode3.SelectedValue.Equals("0"))
            {
                //ddlCode2.Visible = true;
                //ddlCode3.Visible = true;
                ddlCode4.Visible = true;
                BindDdlCode4(Int32.Parse(ddlCode3.SelectedValue));
            }
            else
            {
                BindDdlCode4(0);
            }
        }
    }
}